package org.swan.web.configuration;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.stream.base.MessageBean;
import org.swan.web.exception.BusinessCode;
import org.swan.web.exception.BusinessException;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<MessageBean<Object>> customerException(BusinessException ex) {
        return new ResponseEntity<>(ex.toMessageBean(), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<MessageBean<Object>> customerException(MethodArgumentNotValidException ex) {
        List<String> err = new ArrayList<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            err.add(error.getField() + ":" + error.getDefaultMessage());
        }
        return new ResponseEntity<>(new BusinessException(BusinessCode.PARAMETER_INVALID, err).toMessageBean(), HttpStatus.OK);
    }

}
